﻿using FreeRedis;

namespace Service.Base
{
    public class BaseRedisService : IBaseRedisService
    {
        private readonly IOptions<RedisCon> _Config;
        private RedisClient _redisClient;

        public BaseRedisService(IOptions<RedisCon> config)
        {
            _Config = config;
            _redisClient = new RedisClient(_Config.Value.WriteHosts[0]); // 假设使用第一个写入主机
        }

        public bool ContainsKey(string key)
        {
            return _redisClient.Exists(key);
        }

        public T Get<T>(string key)
        {
            var json = _redisClient.Get<string>(key);
            return json.FromJson<T>();
        }

        public List<T> GetListRange<T>(string key, int start, int count)
        {
            var redisList = _redisClient.LRange<T>(key, start, start + count - 1);
            return redisList?.ToList() ?? new List<T>();
        }

        public bool Remove(string key)
        {
            return _redisClient.Del(key) > 0;
        }

        public bool Set<T>(string key, T value)
        {
            _redisClient.Set(key, value.ToJson());
            return true;
        }

        public bool Set<T>(string key, T value, DateTime expiresAt)
        {
            _redisClient.Set(key, value.ToJson());
            return _redisClient.ExpireAt(key, expiresAt);
        }

        public bool Set<T>(string key, T value, TimeSpan expiresIn)
        {
            _redisClient.Set(key, value.ToJson(), expiresIn);
            return true;
        }
    }
}